package com.lbz.controller.backend;

import com.google.common.collect.Maps;
import com.lbz.common.Constant;
import com.lbz.common.ResponseCode;
import com.lbz.common.ServerResponse;
import com.lbz.entity.Product;
import com.lbz.entity.User;
import com.lbz.service.FileService;
import com.lbz.service.ProductService;
import com.lbz.service.UserService;
import com.lbz.utils.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author 林必昭
 * @Date 2019/6/26 13:41
 */

@Controller
@RequestMapping("/manage/product/")
public class ProductManageController {

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private FileService fileService;

    /**
     * 商品列表
     * @param session
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "list.do")
    @ResponseBody
    public ServerResponse list(HttpSession session,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            return productService.getProductList(pageNum,pageSize);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }
    }

    /**
     * 新增/更新商品
     * 当id传的的时候为更新商品，不传的时候为添加商品
     * @param session
     * @param product
     * @return
     */
    @RequestMapping("save.do")
    @ResponseBody
    public ServerResponse productSave(HttpSession session, Product product){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            return productService.saveOrUpdateProduct(product);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }

    }

    /**
     * 商品详情
     * @param session
     * @param productId
     * @return
     */
    @RequestMapping(value = "detail.do")
    @ResponseBody
    public ServerResponse getDetail(HttpSession session,Integer productId){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            return productService.manageProductDetail(productId);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }
    }

    /**
     * 搜索商品
     * @param session
     * @param productName
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "search.do")
    @ResponseBody
    public ServerResponse search(HttpSession session,
                                 String productName,
                                 Integer productId,
                                 @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                 @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            return productService.searchProduct(productName,productId,pageNum,pageSize);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }
    }

    /**
     * 商品的上下架
     *
     * 商品状态.1-在售 2-下架 3-删除
     *
     * @param session
     * @param productId
     * @param status
     * @return
     */
    @RequestMapping(value = "set_sale_status.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession session,Integer productId,Integer status){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            return productService.setSaleStatus(productId,status);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }

    }

    /**
     * 文件上传
     *
     * 注意：upload_file要对用form表单的<input type="file" name="upload_file">
     * @param session
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "upload.do")
    @ResponseBody
    public ServerResponse upload(HttpSession session,
                                 @RequestParam(value = "upload_file",required = false) MultipartFile file,
                                 HttpServletRequest request){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //校验是否是管理员
        ServerResponse serverResponse = userService.checkRoleAdmin(user);
        if (serverResponse.isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");   //获取upload文件夹的路径
            String targetFileName = fileService.upload(file,path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;

            Map fileMap = Maps.newHashMap();
            fileMap.put("url",url);
            fileMap.put("uri",targetFileName);
            return ServerResponse.createBySuccess(fileMap);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，请以管理员身份登陆");
        }
    }

    /**
     * 富文本上传图片，使用Map集合来保存返回数据，传参1.HttpSession 2.MultipartFile file 3.HttpServletRequest request 4.HttpServletResponse response
     *
     * 要求返回：
     *     "file_path": "http://img.happymmall.com/5fb239f2-0007-40c1-b8e6-0dc11b22779c.jpg",
     *     "msg": "上传成功",
     *     "success": true
     *
     * @param session
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "richText_img_upload.do")
    @ResponseBody
    public Map richTextUpload(HttpSession session,
                              @RequestParam(value = "upload_file",required = false) MultipartFile file,
                              HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = Maps.newHashMap();
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user==null){
            resultMap.put("success",false);
            resultMap.put("msg","请以管理员身份登陆");
            return resultMap;
        }
        if (userService.checkRoleAdmin(user).isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetName = fileService.upload(file,path);
            if (StringUtils.isBlank(targetName)){
                resultMap.put("success",false);
                resultMap.put("msg","上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetName;
            resultMap.put("file_path",url);
            resultMap.put("msg","上传成功");
            resultMap.put("success",true);
            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
            return resultMap;
        }else {
            resultMap.put("success",false);
            resultMap.put("msg","无权限操作");
            return resultMap;
        }
    }
}
